package com.example.nextgen.parser.excel.model;

import cn.hutool.poi.excel.ExcelReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.nextgen.generator.Generator;
import lombok.Data;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author martin
 * @date Created in 2022/11/11 12:21
 * @description
 */
@Data
public class ExcelParserResult {

    private ExcelReader excelReader;

    private Map<String,Object> developForms;

    private List<Sheet> templateSheets;

    private Config config;

    public void setDevelopForms(Map<String, Object> developForms) {
        this.developForms = refresh(developForms,developForms,new TypeReference<Map<String,Object>>(){});
    }

    public void setConfig(Map<String, Object> config) {
        String jsonString = JSON.toJSONString(config);
        Config thisConfig = JSON.parseObject(jsonString, Config.class);
        thisConfig.setNonComplete(hasNonComplete(jsonString));
        this.config =  thisConfig;
    }

    public void refreshConfigFromFroms(){
        if (getConfig().isNonComplete()){
            this.config = refresh(getConfig(),getDevelopForms(),new TypeReference<Config>(){});
        }
    }

    public <T>T refresh(Object source,Object data,TypeReference<T> typeReference){
        String sourceJSON = JSON.toJSONString(source);
        Pattern pattern = Pattern.compile("\\$\\{.+?}");
        Matcher matcher = pattern.matcher(sourceJSON);
        while (matcher.find()){
            String group = matcher.group();
            try {
                String replace = new Generator().freemarkerGen("", group, data);
                sourceJSON = sourceJSON.replace(group,replace.replace("\\","\\\\"));
            }catch (Exception e){
                //do nothing
                continue;
            }
            matcher = pattern.matcher(sourceJSON);
        }
        return JSON.parseObject(sourceJSON,typeReference);
    }

    public boolean hasNonComplete(String source){
        return Pattern.compile("\\$\\{.+?}").matcher(source).find();
    }
}
